import axios from 'axios'
import type { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import { useAccountStore } from '@/stores/account'
import services from '@/services/index'
import router from '@/router'

const BASE_URL = 'http://localhost:8080'

const request: AxiosInstance = axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const authStore = useAccountStore()
    const token = authStore.getToken

    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data
  },
  async (error) => {
    if (error.response?.status === 401) {
      const accountStore = useAccountStore()
      const refreshToken = accountStore.getRefreshToken

      if (refreshToken) {
        try {
          const response = await services.account.refreshToken(refreshToken)

          accountStore.setTokens(response)

          // 重试原请求
          const config = error.config
          config.headers.Authorization = `Bearer ${response.access_token}`
          return axios(config)
        } catch (refreshError) {
          accountStore.clearAuth()
          router.push('/login')
          return Promise.reject(refreshError)
        }
      } else {
        accountStore.clearAuth()
        router.push('/login')
      }
    }
    return Promise.reject(error)
  },
)

export default request
